package com.affablebeans.servlet;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.affablebeans.cart.ShoppingCart;
import com.affablebeans.model.DbContext;
import com.affablebeans.model.entity.Product;

/**
 * 
 * @author Bora SAYINER
 * @since Jan 31, 2015 5:16:06 PM
 * @version 1.0.0
 */
public class DispatcherServlet extends HttpServlet {

	private DbContext dbContext;

	@Override
	public void init() throws ServletException {
		dbContext = (DbContext) getServletContext().getAttribute("dbContext");
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String uri = req.getServletPath();
		if (uri.endsWith("/category")) {
			processCategoryRequest(req);
		} else if (uri.endsWith("/viewCart")) {
			uri = "/cart";
		}
		req.getRequestDispatcher("/WEB-INF/" + uri + ".jsp").forward(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		int productId = Integer.valueOf(req.getParameter("productId"));
		try {
			Product product = dbContext.getProducts().findProductById(productId);
			HttpSession session = req.getSession();
			ShoppingCart shoppingCart = null;
			shoppingCart = (ShoppingCart) session.getAttribute("shoppingCart");
			if (shoppingCart == null) {
				shoppingCart = new ShoppingCart();
				session.setAttribute("shoppingCart", shoppingCart);
			}
			shoppingCart.addProduct(product);
			processCategoryRequest(req);
			req.getRequestDispatcher("/WEB-INF/category.jsp").forward(req, resp);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	private void processCategoryRequest(HttpServletRequest req) {
		int id = 1;
		try {
			HttpSession session = req.getSession();
			if (req.getParameter("id") == null) {
				id = (int) session.getAttribute("selectedCategory");
			} else {
				id = Integer.valueOf(req.getParameter("id"));
				session.setAttribute("selectedCategory", id);
			}
			List<Product> products = dbContext.getProducts().findProductByCategory(id);
			session.setAttribute("products", products);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
